package com.ec.pf.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ec.api.client.UserClient;
import com.ec.common.domain.Result;
import com.ec.common.exception.BadRequestException;
import com.ec.pf.mapper.FamilyElderlyBindingMapper;
import com.ec.pf.pojo.BindingInfo;
import com.ec.pf.pojo.FamilyElderlyBinding;
import com.ec.pf.service.FamilyElderlyBindingService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.List;

@Service
@RequiredArgsConstructor
public class FamilyElderlyBindingServiceImpl extends ServiceImpl<FamilyElderlyBindingMapper, FamilyElderlyBinding> implements FamilyElderlyBindingService {

    private final FamilyElderlyBindingMapper familyElderlyBindingMapper;
    private final UserClient userClient;

    // 家属申请绑定老人
    @Override
    @Transactional(rollbackFor = Exception.class)
    public FamilyElderlyBinding bindFamilyToElderly(Long familyUserId, Long elderlyUserId) {
        FamilyElderlyBinding binding = new FamilyElderlyBinding();
        binding.setFamilyUserId(familyUserId);
        binding.setElderlyUserId(elderlyUserId);
        binding.setStatus("待审批");

        Timestamp currentTimestamp = new Timestamp(System.currentTimeMillis());
        binding.setCreatedAt(currentTimestamp);
        binding.setUpdatedAt(currentTimestamp);

        boolean saved = this.save(binding);
        if (!saved) {
            throw new RuntimeException("家属绑定老人申请失败");
        }
        return binding;
    }

    // 老人申请绑定家属
    @Override
    @Transactional(rollbackFor = Exception.class)
    public FamilyElderlyBinding bindElderlyToFamily(Long familyUserId, Long elderlyUserId) {
        FamilyElderlyBinding binding = new FamilyElderlyBinding();
        binding.setFamilyUserId(familyUserId);
        binding.setElderlyUserId(elderlyUserId);
        binding.setStatus("待审批");

        Timestamp currentTimestamp = new Timestamp(System.currentTimeMillis());
        binding.setCreatedAt(currentTimestamp);
        binding.setUpdatedAt(currentTimestamp);

        boolean saved = this.save(binding);
        if (!saved) {
            throw new RuntimeException("老人绑定家属申请失败");
        }
        return binding;
    }

    // 批准绑定申请
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean approveBinding(Long bindingId, Long adminId) {
        FamilyElderlyBinding binding = this.getById(bindingId);
        if (binding == null || !(binding.getStatus().equals("待审批"))) {
            throw new RuntimeException("绑定申请不存在或已处理");
        }
        binding.setStatus("审批通过");
        binding.setApprovedByAdminId(adminId);
        binding.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
        return this.updateById(binding);
    }

    // 拒绝绑定申请
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean rejectBinding(Long bindingId) {
        FamilyElderlyBinding binding = this.getById(bindingId);
        if (binding == null || !(binding.getStatus().equals("待审批"))) {
            throw new RuntimeException("绑定申请不存在或已处理");
        }
        binding.setStatus("已拒绝");
        binding.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
        return this.updateById(binding);
    }

    // 管理员模糊查询绑定关系
    @Override
    public Page<BindingInfo> getBindingByFamilyAndElderlyNames(String familyName, String elderlyName, int page, int size) {
        // 创建 Page 对象，指定页码和每页大小
        Page<BindingInfo> pageRequest = new Page<>(page, size);

        // 查询分页数据
        return familyElderlyBindingMapper.selectBindingWithDetailsPaged(pageRequest, familyName, elderlyName);
    }

    // 管理员分页查询绑定申请记录
    @Override
    public Page<BindingInfo> getBindingDetails(int page, int size) {
        // 创建 Page 对象，指定页码和每页大小
        Page<BindingInfo> bindingInfoPage = new Page<>(page, size);

        // 查询分页数据
        return familyElderlyBindingMapper.selectBindingAllPaged(bindingInfoPage);
    }

    // 分页查询家属自己发起的绑定申请记录
    @Override
    public Page<BindingInfo> getSelfBindingDetails(Long familyUserId, int page, int size) {
        // 创建 Page 对象，指定页码和每页大小
        Page<BindingInfo> bindingInfoPage = new Page<>(page, size);

        // 查询分页数据
        return familyElderlyBindingMapper.selectSelfBindingFamilyPaged(bindingInfoPage, familyUserId);
    }

    // 分页查询老人自己发起的绑定申请记录
    @Override
    public Page<BindingInfo> getElderlyBindingDetails(Long elderlyUserId, int page, int size) {
        // 创建 Page 对象，指定页码和每页大小
        Page<BindingInfo> bindingInfoPage = new Page<>(page, size);

        // 查询分页数据
        return familyElderlyBindingMapper.selectSelfBindingElderlyPaged(bindingInfoPage, elderlyUserId);
    }

    // 删除家属或老人自己的绑定申请记录
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteSelfBinding(Long bindingId, Long userId) {
        FamilyElderlyBinding binding = this.getById(bindingId);
        if (binding == null) {
            throw new RuntimeException("绑定记录不存在");
        }
        if (!binding.getFamilyUserId().equals(userId) && !binding.getElderlyUserId().equals(userId)) {
            throw new RuntimeException("只能删除自己发起的绑定！");
        }
        return this.removeById(bindingId);
    }

    // 管理员删除绑定申请记录
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBindingByAdmin(Long bindingId) {
        FamilyElderlyBinding binding = this.getById(bindingId);
        if (binding == null) {
            throw new RuntimeException("绑定记录不存在！");
        }
        return this.removeById(bindingId);
    }

    // 管理员批量删除绑定申请记录
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDeleteBindingByAdmin(List<Long> bindingIds) {
        if (bindingIds == null || bindingIds.isEmpty()) {
            throw new RuntimeException("没有绑定ID可以删除");
        }
        return this.removeByIds(bindingIds);
    }
}
